//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by 胡阳 on 16/5/19.
//  Copyright © 2016年 young4ever. All rights reserved.
//

import UIKit
import SVProgressHUD

let reuseID = "homeCellReuseID"
class HomeTableViewController: BaseTableViewController {
    /// 保存微博数组
    var statuses : [Status]?
        {
        didSet{
            // 当给statuses赋完值时 , 刷新表格
            tableView.reloadData()
        }
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // 1.未登录加载游客视图
        if !userLogin {
            
            visitorView?.setupVisitorInfo(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人回这里看看有什么惊喜")
            return
        }
        
        // 2.初始化导航条按钮
        setupNavigationItem()
        
        // 3.接收通知改变titleButton箭头
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.changeTitleButtonArrow), name: WBPopoverAnimatorWillShowNotification , object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.changeTitleButtonArrow), name: WBPopoverAnimatorWillHideNotification , object: nil)
        
        // 3.1接收图片点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.imageHasbeenTaped(_:)), name: WeiboStatusPictureTapNotification, object: nil)
        
        // 注册2个cell<原创和转发>
        tableView.registerClass(StatusNormalTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellType.Normal.rawValue)
        tableView.registerClass(StatusForwardTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellType.Forward.rawValue)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 4.添加下拉刷新控件
        refreshControl = HomeRefreshControl()
        refreshControl?.addTarget(self, action: #selector(HomeTableViewController.loadData), forControlEvents: .ValueChanged)
        
        // 5.加载微博数据
        loadData()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    var pullUpRefresh : Bool = false;
    
    
    @objc private func loadData()
    {
        SVProgressHUD.show()
        
        /*
         1.默认最新返回20条数据
         2.since_id : 会返回比since_id大的微博
         3.max_id: 会返回小于等于max_id的微博
         
         每条微博都有一个微博ID, 而且微博ID越后面发送的微博, 它的微博ID越大
         递增
         
         新浪返回给我们的微博数据, 是从大到小的返回给我们的
         */
        // 拿到第一条微博的id
        var since_id = statuses?.first?.id ?? 0
        
        var max_id = 0
        
        if pullUpRefresh {
            since_id = 0;
            max_id = statuses?.last?.id ?? 0
        }
        
        
        Status.loadStatues(since_id,max_id: max_id) { (models, error) in
            
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                return
            }
            
            // 下拉刷新把最新的微博插入以前的微博数组<self.statuses>中
            if since_id > 0 {
                
                self.statuses = models! + self.statuses!
                
                self.showNewStatusAlert(models!.count)
            }else if max_id > 0{
                
                self.statuses = self.statuses! + models!
            }else {
                // 否则, 把第一次请求的数组直接赋值给 self.statuses
                self.statuses = models
            }
            
            
            
            SVProgressHUD.dismiss()
        }
    }
    
    private func showNewStatusAlert(count: Int)
    {
        newStatusLabel.hidden = false
    
        let text = (count == 0) ? "没有新的微博~" : "更新了\(count)条新微薄~.~"
        
        newStatusLabel.text = text
        
        UIView.animateWithDuration(2.0, animations: {
            self.newStatusLabel.transform = CGAffineTransformMakeTranslation(0, self.newStatusLabel.frame.size.height)
            }) { (_) in
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), {
                    UIView.animateWithDuration(1.5, animations: {
                        self.newStatusLabel.transform = CGAffineTransformIdentity
                        }, completion: { (_) in
                            self.newStatusLabel.hidden = true
                    })
                })
        }
    }
    
    func imageHasbeenTaped(notify: NSNotification){
    
        // 注意: 如果通过通知传递数据, 一定要判断数据是否存在
        guard let indexPath = notify.userInfo![WeiboStatusPictureIndexKey] as? NSIndexPath else
        {
            print("没有indexPath")
            return
        }
        
        guard let urls = notify.userInfo![WeiboStatusPictureURLsKey] as? [NSURL] else
        {
            print("没有配图")
            return
        }
        let photoBrowser = PhotoBrowserController(index: indexPath.item, urls: urls)
        
        presentViewController(photoBrowser, animated: true, completion: nil)
    }
    
    func changeTitleButtonArrow() {
        let btn = navigationItem.titleView as! TitleButton
        btn.selected = !btn.selected
    }
    
    
    func leftItemClicked() {
        print(#function)
    }
    
    func rightItemClicked() {
//        print(#function)
        let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        presentViewController(vc!, animated: true, completion: nil)
    }
    
    func titleButtonClicked(btn: TitleButton) { 
        
        // 2.弹出菜单
        let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
//        vc.delegate = self
        // 2.1设置转场代理
        // 默认的情况下modal会移除当前的view,显示modal推出俺的这个view
        // 自定的转场的话就不会移除当前的view
        vc?.transitioningDelegate = animator
        // 2.2设置转场样式
        vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc!, animated: true, completion: nil)
    }
    
    // MARK:- 懒加载
    private lazy var newStatusLabel : UILabel = {
    
        let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        label.font = UIFont.systemFontOfSize(18)
        label.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 44)
        label.hidden = true
        self.navigationController?.navigationBar .insertSubview(label, atIndex: 0)
        return label
    }()

    // MARK:- 私有方法
    /**
     初始化导航条
     */
    private func setupNavigationItem() {
        
        // 初始化左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.packageButtonToItem("navigationbar_friendattention",target: self, action: #selector(HomeTableViewController.leftItemClicked))
        
        // 快捷键修改名称: command + control + e
        navigationItem.rightBarButtonItem = UIBarButtonItem.packageButtonToItem("navigationbar_pop",target: self, action: #selector(HomeTableViewController.rightItemClicked))
        
        // 初始化标题按钮
        let titleBtn = TitleButton()
        titleBtn.setTitle("ALittleNasty ", forState: UIControlState.Normal)
        titleBtn.addTarget(self, action: #selector(HomeTableViewController.titleButtonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    // 一定要保存一个对象来保存自定义转场对象, 否则会报错
    private lazy var animator: PopoverAnimator = {
    
        let anim = PopoverAnimator()
        let positionX = (UIScreen.mainScreen().bounds.size.width - 200)/2
        anim.presentFrame = CGRect(x: positionX, y: 56, width: 200, height: 250)
        return anim
    }()
    
    // 缓存行高的字典
    var rowCache : [Int : CGFloat] = [Int : CGFloat]()
    
    override func didReceiveMemoryWarning() {
        // 清空缓存
        rowCache.removeAll()
    }
}

extension HomeTableViewController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let model = statuses![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellType.cellType(model), forIndexPath: indexPath) as! StatusTableViewCell
        cell.model = model
        
        // 自动上拉加载更多<当滚动到最后一条微博时自动加载>
        let count = statuses?.count ?? 0 ;
        if count - 1 == indexPath.row {
            
            pullUpRefresh = true
            loadData()
        }
        
        return cell
    }
  
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        // 1.取出对应的模型
        let status = statuses![indexPath.row]
        
        if let cacheHeight = rowCache[status.id] {
            // 如果缓存了就直接取
            return cacheHeight
        }
        
        // 2.拿到cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellType.cellType(status)) as! StatusTableViewCell
        
        // 3.拿到对应行的行高
        let height = cell.rowHeight(status) 
        
        // 3.1 缓存行高
        rowCache[status.id] = height
        
        // 4.设置行高
        return height
    }
}

